<template>
    <div class="cart-container">
        <!-- <div class="cart-header">
            <h1>购物车</h1>
            <span class="cart-count">共 {{ totalItems }} 件商品</span>
        </div> -->

        <div class="cart-content">
            <!-- 购物车为空时显示 -->
            <div v-if="cartItems.length === 0" class="empty-cart">
                <el-icon size="64" color="#ccc">
                    <ShoppingCart />
                </el-icon>
                <h3>购物车是空的</h3>
                <p>快去挑选心仪的商品吧</p>
                <el-button type="primary" @click="goToProducts">去购物</el-button>
            </div>

            <!-- 购物车商品列表 -->
            <div v-else class="cart-items">
                <!-- 表头 -->
                <div class="cart-table-header">
                    <div class="header-select"></div>
                    <div class="header-product">商品信息</div>
                    <div class="header-price">单价</div>
                    <div class="header-quantity">数量</div>
                    <div class="header-amount">金额</div>
                    <div class="header-action">操作</div>
                </div>

                <!-- 按店铺分组的商品列表 -->
                <div v-for="shop in groupedItems" :key="shop.shopName" class="shop-group">
                    <!-- 店铺信息 -->
                    <div class="shop-header">
                        <div class="shop-select">
                            <el-checkbox v-model="shop.selected" @change="toggleShopSelect(shop)"
                                :indeterminate="shop.indeterminate" />
                        </div>
                        <div class="shop-name">{{ shop.shopName }}</div>
                    </div>

                    <!-- 店铺商品列表 -->
                    <div class="shop-items">
                        <div v-for="item in shop.items" :key="item.id" class="cart-item">
                            <div class="item-select">
                                <el-checkbox v-model="item.selected" @change="updateShopSelection(shop)" />
                            </div>

                            <div class="item-product">
                                <div class="item-image">
                                    <img :src="item.image" :alt="item.title" />
                                </div>
                                <div class="item-info">
                                    <h3 class="item-title">{{ item.title }}</h3>
                                    <div class="item-spec">{{ item.spec }}</div>
                                </div>
                            </div>

                            <div class="item-price">
                                <span class="price-symbol">¥</span>
                                <span class="price-value">{{ item.price.toFixed(2) }}</span>
                            </div>

                            <div class="item-quantity">
                                <div class="quantity-selector">
                                    <el-button @click="decreaseQuantity(item)"
                                        :disabled="item.quantity <= 1">-</el-button>
                                    <span class="quantity">{{ item.quantity }}</span>
                                    <el-button @click="increaseQuantity(item)">+</el-button>
                                </div>
                            </div>

                            <div class="item-amount">
                                <span class="amount-symbol">¥</span>
                                <span class="amount-value">{{ (item.price * item.quantity).toFixed(2) }}</span>
                            </div>

                            <div class="item-action">
                                <el-button type="danger" size="small" @click="removeItem(item.id)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 购物车底部 -->
            <div v-if="cartItems.length > 0" class="cart-footer">
                <div class="cart-summary">
                    <div class="select-all">
                        <el-checkbox v-model="selectAll" @change="toggleSelectAll">
                            全选
                        </el-checkbox>
                    </div>

                    <div class="summary-info">
                        <span>共{{ selectedCount }}件</span>
                        <div class="total-price">
                            <span>合计(不含运费): </span>
                            <span class="price-symbol">¥</span>
                            <span class="price-value">{{ totalPrice.toFixed(2) }}</span>
                        </div>
                    </div>

                    <div class="checkout-actions">
                        <el-button type="primary" size="large" @click="checkout" :disabled="selectedCount === 0">
                            结算
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ShoppingCart, Delete } from '@element-plus/icons-vue'

const router = useRouter()

// 购物车数据
const cartItems = ref([
    {
        id: 1,
        title: '【原神】莫娜·星天水镜Ver.1/7手办 现货',
        spec: '莫娜·星天水镜Ver.1/7手办',
        price: 1168.00,
        quantity: 2,
        image: 'https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/149433e311027bd440c5308731e5f8a2_4642751770306204096.jpeg',
        shopName: '原神万有铺子',
        selected: true
    },
    {
        id: 2,
        title: '「崩坏:星穹铁道」叽米的会客室系列马口铁徽章套组',
        spec: '流萤,【以规格标注为准,预售200天内发货】',
        price: 30.00,
        quantity: 1,
        image: 'https://act-webstatic.mihoyo.com/upload/mall/2025/06/11/40a7829bf698099cfc25f0616bbe9c76_3146889449930295136.jpg',
        shopName: '货全杂货铺',
        selected: false
    },
    {
        id: 3,
        title: '「崩坏:星穹铁道」光锥系列亚克力流沙立牌',
        spec: '偏偏希望无价',
        price: 68.00,
        quantity: 1,
        image: 'https://act-webstatic.mihoyo.com/upload/mall/2025/07/21/fba71928875619aae089cd47ce826fb4_7831665216138524295.jpg',
        shopName: '货全杂货铺',
        selected: false
    }
])

// 计算属性
const totalItems = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const selectedCount = computed(() => {
    return cartItems.value.filter(item => item.selected).length
})

const totalPrice = computed(() => {
    return cartItems.value
        .filter(item => item.selected)
        .reduce((total, item) => total + (item.price * item.quantity), 0)
})

const selectAll = computed({
    get() {
        return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
    },
    set(value) {
        cartItems.value.forEach(item => item.selected = value)
    }
})

// 按店铺分组
const groupedItems = computed(() => {
    const groups = {}
    cartItems.value.forEach(item => {
        if (!groups[item.shopName]) {
            groups[item.shopName] = {
                shopName: item.shopName,
                items: [],
                selected: false,
                indeterminate: false
            }
        }
        groups[item.shopName].items.push(item)
    })

    // 计算每个店铺的选择状态
    Object.values(groups).forEach((shop: any) => {
        const selectedItems = shop.items.filter(item => item.selected)
        shop.selected = selectedItems.length === shop.items.length
        shop.indeterminate = selectedItems.length > 0 && selectedItems.length < shop.items.length
    })

    return Object.values(groups)
})

// 方法
const increaseQuantity = (item: any) => {
    item.quantity++
    updateTotal()
}

const decreaseQuantity = (item: any) => {
    if (item.quantity > 1) {
        item.quantity--
        updateTotal()
    }
}

const removeItem = async (itemId: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const index = cartItems.value.findIndex(item => item.id === itemId)
        if (index > -1) {
            cartItems.value.splice(index, 1)
            ElMessage.success('商品已删除')
        }
    } catch {
        // 用户取消删除
    }
}

const toggleSelectAll = () => {
    updateTotal()
}

const toggleShopSelect = (shop: any) => {
    shop.items.forEach(item => {
        item.selected = shop.selected
    })
    updateTotal()
}

const updateShopSelection = (shop: any) => {
    const selectedItems = shop.items.filter(item => item.selected)
    shop.selected = selectedItems.length === shop.items.length
    shop.indeterminate = selectedItems.length > 0 && selectedItems.length < shop.items.length
    updateTotal()
}

const updateTotal = () => {
    // 这里可以添加更新总价的逻辑
}

const checkout = () => {
    const selectedItems = cartItems.value.filter(item => item.selected)
    if (selectedItems.length === 0) {
        ElMessage.warning('请选择要结算的商品')
        return
    }

    ElMessage.success(`正在跳转到结算页面，共 ${selectedItems.length} 件商品`)
    // 这里可以跳转到结算页面
}

const goToProducts = () => {
    router.push('/shop/products')
}
</script>

<style scoped>
.cart-container {
    padding: 12px 12px 0 12px;
    background: #fff;
    min-height: 100vh;
    position: relative;
    /* 移除可能导致横向滚动的设置 */
}

.cart-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e9ecef;
}

.cart-header h1 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

.cart-count {
    font-size: 14px;
    color: #666;
}

/* 购物车内容区域 */
.cart-content {
    /* 移除粘性定位相关的底部内边距 */
}

/* 空购物车样式 */
.empty-cart {
    text-align: center;
    padding: 80px 20px;
    color: #999;
}

.empty-cart h3 {
    margin: 16px 0 8px 0;
    font-size: 18px;
    color: #666;
}

.empty-cart p {
    margin: 0 0 24px 0;
    font-size: 14px;
}

/* 购物车表格 */
.cart-items {
    margin-bottom: 32px;
}

/* 表头 */
.cart-table-header {
    display: grid;
    grid-template-columns: 60px 1fr 120px 120px 120px 80px;
    gap: 12px;
    align-items: center;
    padding: 16px 20px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    font-weight: 500;
    color: #333;
    font-size: 14px;
    margin-bottom: 16px;
    /* 确保表头不会换行 */
    white-space: nowrap;
}

.header-select {
    text-align: center;
}

.header-product {
    padding-left: 16px;
}

.header-price,
.header-quantity,
.header-amount,
.header-action {
    text-align: center;
}

/* 店铺分组 */
.shop-group {
    margin-bottom: 16px;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    overflow: hidden;
}

.shop-header {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px 20px;
    background: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
}

.shop-select {
    flex-shrink: 0;
}

.shop-name {
    font-size: 14px;
    font-weight: 500;
    color: #333;
}

/* 商品列表 */
.shop-items {
    background: #fff;
}

.cart-item {
    display: grid;
    grid-template-columns: 60px 1fr 120px 120px 120px 80px;
    gap: 12px;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.3s ease;
    /* 确保商品行不会换行 */
    min-width: 0;
}

.cart-item:last-child {
    border-bottom: none;
}

.cart-item:hover {
    background: #fafafa;
}

.item-select {
    text-align: center;
}

.item-product {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
    overflow: hidden;
    /* 确保商品信息区域不会换行 */
    flex-shrink: 1;
}

.item-image {
    width: 80px;
    height: 80px;
    border-radius: 6px;
    overflow: hidden;
    flex-shrink: 0;
}

.item-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.item-info {
    flex: 1;
    min-width: 0;
    overflow: hidden;
}

.item-title {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin: 0 0 4px 0;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.item-spec {
    font-size: 12px;
    color: #666;
    line-height: 1.4;
}

.item-price,
.item-amount {
    display: flex;
    align-items: baseline;
    justify-content: center;
    gap: 2px;
}

.price-symbol,
.amount-symbol {
    font-size: 12px;
    color: #ff4d4f;
    font-weight: 500;
}

.price-value,
.amount-value {
    font-size: 16px;
    color: #ff4d4f;
    font-weight: 600;
}

.quantity-selector {
    display: flex;
    align-items: center;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    width: fit-content;
    margin: 0 auto;
    max-width: 100%;
}

.quantity-selector .el-button {
    border: none;
    border-radius: 0;
    width: 32px;
    height: 32px;
    padding: 0;
}

.quantity {
    padding: 0 12px;
    min-width: 40px;
    text-align: center;
    font-size: 14px;
    color: #333;
}

.item-action {
    text-align: center;
}

/* 购物车底部 */
.cart-footer {
    background: #fff;
    padding: 16px 20px;
    /* box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1); */
    border-top: 1px solid #e9ecef;
}

.cart-summary {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24px;
}

.select-all {
    flex-shrink: 0;
}

.summary-info {
    display: flex;
    align-items: center;
    gap: 24px;
    flex: 1;
}

.summary-info span {
    font-size: 14px;
    color: #666;
}

.total-price {
    display: flex;
    align-items: baseline;
    gap: 2px;
}

.total-price .price-symbol {
    font-size: 14px;
}

.total-price .price-value {
    font-size: 20px;
}

.checkout-actions {
    flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .cart-container {
        padding: 16px 12px 0 12px;
    }

    .cart-table-header {
        display: none;
    }

    .cart-item {
        grid-template-columns: 1fr;
        gap: 12px;
        text-align: center;
        padding: 16px;
    }

    .item-product {
        flex-direction: column;
        text-align: center;
    }

    .item-image {
        width: 120px;
        height: 120px;
        margin: 0 auto;
    }

    .cart-summary {
        flex-direction: column;
        gap: 16px;
        text-align: center;
    }

    .summary-info {
        flex-direction: column;
        gap: 12px;
    }

    .checkout-actions {
        width: 100%;
    }

    .cart-footer {
        padding: 12px 16px;
        border-top: 1px solid #e9ecef;
    }
}
</style>
